package com.webdrider.servlet.util.parser.system;

import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractResponse;
import com.common.security.exceptions.HTTPException;
import com.common.security.exceptions.ParserException;
import com.webdrider.model.requests.system.CreateChannelRequest;
import com.webdrider.model.response.system.CreateChannelResponse;
import com.webdrider.servlet.abstracts.XMLParserBase;
import com.webdrider.servlet.util.HTTPProtocol;

public class CreateChannelXMLParser extends XMLParserBase {

	@Override
	public AbstractRequest parseRequest(InputStream stream) throws ParserException, HTTPException {
		CreateChannelRequest request = new CreateChannelRequest();
		
		Document document = createDocument(stream);
		
		Node actionNode = getActionNode(document);
		Node contentNode = getContentNode(document);
		
		insertAction(actionNode, request);
		Element element = getContent(contentNode);
		
		Element token = getElement(element, HTTPProtocol.GAME);
		request.setUserToken(token.getAttribute(HTTPProtocol.ATTRIBUTE_VALUE));
		
		return request;
	}

	@Override
	public String parseResponse(AbstractResponse abstractResponse) throws ParserException {
		CreateChannelResponse response = null;
		if (abstractResponse instanceof CreateChannelResponse) {
			response = (CreateChannelResponse) abstractResponse;
		} else {
			throw new ParserException(ParserException.RESPONSE_MATCH_ERROR);
		}
		
		StringBuilder builder = new StringBuilder();

		builder.append(HTTPProtocol.RESPONSE_TAG);
		builder.append(HTTPProtocol.CLOSE_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(getAction(response.getRequestAction()));
		builder.append(HTTPProtocol.CONTENT_TAG);
		builder.append(getGameId(response.getToken()));
		builder.append(HTTPProtocol.CONTENT_END_TAG);
		builder.append(HTTPProtocol.END_LINE);
		builder.append(HTTPProtocol.RESPONSE_END_TAG);
		
		return builder.toString();
	}

}
